package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseListView;
import com.haochang.base.BaseScrollView;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.adapter.order.OrderChangeAdapter;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.MenuInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.ShopCartData;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase.Mode;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase.OnRefreshListener2;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshListView;
import com.haochang.chunkvod.view.vod.menu.MenuLayout;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/6/1 16:27
 *         点餐-更换商品
 */

public class OrderChangeActivity extends BaseActivity
{
	private TitleView titleView;
	private BaseEditText et_search;
	private ImageView img_del;
	private ImageView img_to_top;
	private MenuLayout tabSwitcher;
	private BaseScrollView scrollView;
	private PullToRefreshListView listView;
	private OrderChangeAdapter orderChangeAdapter;
	private PullToRefreshListView search_listView;
	private BaseTextView tv_no_data;
	private OrderData orderData;
	private ShopCartData shopCartData;
	private String roomNum;
	private String roomId;
	private String billId;
	private String menuId;
	private String charging_room_type_id;
	private List<MenuInfo> menuInfoList = new ArrayList<MenuInfo>();//菜单信息
	private List<GoodsInfo> goodsInfoList = new ArrayList<GoodsInfo>();//商品列表
	private List<GoodsInfo> searchGoodsInfoList = new ArrayList<GoodsInfo>();//搜索商品列表
	private FoodDetailInfo swapInfo = null;//被更换的商品
	private int is_active;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
		roomNum = getIntent().getStringExtra(IntentKey.ROOM_NUM);
		roomId = getIntent().getStringExtra(IntentKey.ROOM_ID);
		billId = getIntent().getStringExtra(IntentKey.BILL_ID);
		charging_room_type_id = getIntent().getStringExtra(IntentKey.CHARGING_ROOM_TYPE_ID);
		swapInfo = (FoodDetailInfo) getIntent().getSerializableExtra(IntentKey.GOODSINFO);
	}

	@Override
	public void initData()
	{
		orderData = new OrderData(OrderChangeActivity.this);
		shopCartData = new ShopCartData(OrderChangeActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_order);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(String.format(roomNum)).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(OrderChangeActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});
		et_search = (BaseEditText) findViewById(R.id.et_search);
		et_search.addTextChangedListener(textWatcher);
		img_del = (ImageView) findViewById(R.id.img_del);
		img_del.setOnClickListener(mOnBaseClickListener);
		tabSwitcher = (MenuLayout) findViewById(R.id.tabSwitcher);
		listView = (PullToRefreshListView) findViewById(R.id.listView);
		listView.setMode(Mode.PULL_FROM_END);
		listView.setOnScrollListener(onScrollListener);
		listView.setOnRefreshListener(new OnRefreshListener2<BaseListView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//下拉刷新
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//上拉加载更多
				getListDataByMenuId(menuId, roomId, billId, false, false);
			}
		});
		scrollView = (BaseScrollView) findViewById(R.id.scrollView);
		search_listView = (PullToRefreshListView) findViewById(R.id.search_listView);
		search_listView.setMode(Mode.PULL_FROM_END);
		search_listView.setOnScrollListener(onScrollListener);
		search_listView.setOnRefreshListener(new OnRefreshListener2<BaseListView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//下拉刷新
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<BaseListView> refreshView)
			{
				//上拉加载更多
				getListDataByKeyWord(roomId, searchGoodsInfoList.size());
			}
		});
		tv_no_data = (BaseTextView) findViewById(R.id.tv_no_data);
		img_to_top = (ImageView) findViewById(R.id.img_to_top);
		img_to_top.setOnClickListener(mOnBaseClickListener);
		orderChangeAdapter = new OrderChangeAdapter(OrderChangeActivity.this, R.layout.item_order_list_layout, goodsInfoList);
		orderChangeAdapter.setChangeData(swapInfo);
		listView.setAdapter(orderChangeAdapter);
		search_listView.setAdapter(orderChangeAdapter);
		search_listView.setVisibility(View.GONE);
		orderData.requestMenu(billId, new OrderData.IMenuListener()
		{
			@Override
			public void onRequestSuccess(List<MenuInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					menuInfoList.addAll(list);
					refreshTabSwitcher();
					getListDataByMenuId(menuInfoList.get(0).getMenuId(), roomId, billId, true, false);
				}
			}
		});
	}

	/**
	 * 根据菜单id获取商品数据
	 *
	 * @param menuId
	 * @param roomId
	 * @param billId
	 * @param isLoading
	 * @param fromMenu
	 */
	private void getListDataByMenuId(String menuId, String roomId, String billId, boolean isLoading, boolean fromMenu)
	{
		if (fromMenu)
			goodsInfoList.clear();
		orderData.requestOrderFood(menuId, roomId, billId, isLoading, goodsInfoList.size() + "", new OrderData.IOrderFoodListener()
		{
			@Override
			public void onRequestSuccess(List<GoodsInfo> list, boolean clear, int isActive)
			{
				is_active = isActive;
				if (clear)
					goodsInfoList.clear();
				if (!CollectionUtils.isEmpty(list))
					addGoodsData(true, list);
				listView.setVisibility(View.VISIBLE);
				orderChangeAdapter.replaceAll(goodsInfoList);
			}

			@Override
			public void onFinish()
			{
				//当前没关闭 并且 在刷新
				if (!isFinishing() && listView.isRefreshing())
				{
					//结束
					listView.onRefreshComplete();
				}
			}
		});
	}

	/**
	 * 根据关键字获取商品数据
	 *
	 * @param roomId
	 * @param offset
	 */
	private void getListDataByKeyWord(String roomId, int offset)
	{
		orderData.requestSearchOrderFood(String.valueOf(is_active), charging_room_type_id, et_search.getText().toString().trim(), roomId, billId, false,
				offset + "", new OrderData.IOrderFoodListener()
				{
					@Override
					public void onRequestSuccess(List<GoodsInfo> list, boolean clear, int isActive)
					{
						is_active = isActive;
						if (clear)
							searchGoodsInfoList.clear();
						if (!CollectionUtils.isEmpty(list))
							addGoodsData(false, list);
						orderChangeAdapter.replaceAll(searchGoodsInfoList);
						if (!CollectionUtils.isEmpty(searchGoodsInfoList))
						{
							tv_no_data.setVisibility(View.GONE);
							search_listView.setVisibility(View.VISIBLE);
						} else
						{
							tv_no_data.setVisibility(View.VISIBLE);
							search_listView.setVisibility(View.GONE);
						}
					}

					@Override
					public void onFinish()
					{
						if (!isFinishing() && search_listView.isRefreshing())
						{
							//结束
							search_listView.onRefreshComplete();
						}
					}
				});
	}

	/**
	 * 添加数据源，套餐或者活动自动过滤掉
	 *
	 * @param list
	 */
	private void addGoodsData(boolean flag, List<GoodsInfo> list)
	{
		for (GoodsInfo goodInfo : list)
		{
			if (goodInfo.getGoods_type() == VodConstant.RETAIL_TYPE)
				if (flag)
					goodsInfoList.add(goodInfo);
				else
					searchGoodsInfoList.add(goodInfo);
		}
	}

	/**
	 * 刷新菜单
	 */
	private void refreshTabSwitcher()
	{
		for (MenuInfo info : menuInfoList)
		{
			//活动或者赠送菜单不显示
			if (!TextUtils.equals(info.getMenuId(), "a40c6662-345b-11e6-917b-000c2953e16d")
					&& !TextUtils.equals(info.getMenuId(), "8a4fe06e-345b-11e6-928a-000c2953e16d"))
				tabSwitcher.addTab(info);
		}
		tabSwitcher.setOnTabChangedListener(new MenuLayout.OnTabChangedListener()
		{
			@Override
			public void onTabChanged(int last, int current, String mId, int is_give)
			{
				menuId = mId;
				getListDataByMenuId(mId, roomId, billId, false, true);
			}
		});
	}

	private AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener()
	{
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			if (getScrollY() > 2)
				img_to_top.setVisibility(View.VISIBLE);
			else
				img_to_top.setVisibility(View.GONE);
		}
	};

	/**
	 * 计算当前listview滚动的距离，因距离不确定，用可见条数代替
	 *
	 * @return
	 */
	public int getScrollY()
	{
		int firstVisiblePosition = 0;
		if (TextUtils.isEmpty(et_search.getText().toString().trim()))
		{
			firstVisiblePosition = listView.getRefreshableView().getFirstVisiblePosition();
		} else
		{
			firstVisiblePosition = listView.getRefreshableView().getFirstVisiblePosition();
		}
		return firstVisiblePosition;
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_del:
				et_search.setText("");
				break;
			case R.id.img_to_top:
				if (TextUtils.isEmpty(et_search.getText().toString().trim()))
					listView.getRefreshableView().smoothScrollToPosition(0);
				else
					search_listView.getRefreshableView().smoothScrollToPosition(0);
				break;
			default:
				break;
			}
		}
	};

	private TextWatcher textWatcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{

		}

		@Override
		public void afterTextChanged(Editable s)
		{
			if (!et_search.getText().toString().trim().equals(""))
			{
				img_del.setVisibility(View.VISIBLE);
				scrollView.setVisibility(View.GONE);
				listView.setVisibility(View.GONE);
				getListDataByKeyWord(roomId, 0);
			} else
			{
				img_del.setVisibility(View.GONE);
				tv_no_data.setVisibility(View.GONE);
				search_listView.setVisibility(View.GONE);
				scrollView.setVisibility(View.VISIBLE);
				listView.setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IntentCode.FLAVOR_REQUEST && resultCode == RESULT_OK)
		{
			GoodsInfo info = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
			if (swapInfo != null && info != null)
				shopCartData.requestChangeGoods(swapInfo.getD_id_value(), info, new ShopCartData.IOrderGoodsChangeListener()
				{
					@Override
					public void onRequestSuccess()
					{
						ToastUtils.showText(OrderChangeActivity.this, "更换商品成功");
						setResult(RESULT_OK);
						finish();
					}

					@Override
					public void onFail(int errno, String errMsg)
					{
						ToastUtils.showText(OrderChangeActivity.this, errMsg);
					}
				});
		}
	}

}
